<?php
namespace app\controllers;

use Yii;
use yii\db\Query;
use yii\helpers\Url;

class FormController extends BaseController
{

    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            $db = (new Query())->from('form');
            $count = $db->count('id',$this->callcenter_db);

            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $db->offset(($page-1)*$limit)->limit($limit)->all($this->callcenter_db);
            foreach ($data as &$d){
                $d['edit_url'] = Url::to(['edit','id'=>$d['id']]);
                $d['destroy_url'] = Url::to(['destroy','id'=>$d['id']]);
                $d['status_name'] = $d['estatus']=='A'?'<span style="color: green">激活</span>':'<span style="color: red">未激活</span>';
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('index');
    }

    /**
     * 添加表单
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $formid = (new Query())->from('form')->max('id',$this->callcenter_db);
            $formid++;
            $db = $this->callcenter_db;
            $transaction = $db->beginTransaction();
            try{
                //写入form表
                $db->createCommand()->insert('form',[
                    'id' => $formid,
                    'nombre' => $data['nombre'],
                    'descripcion' => $data['descripcion'],
                    'estatus' => 'A',
                ])->execute();
                //写入form_field表
                if (!empty($data['form_fields'])){
                    $column = ['id_form','etiqueta','tipo','orden','value'];
                    $column_data = [];
                    foreach ($data['form_fields'] as $d){
                        if ($d['tipo']=='LIST'){
                            $value = implode(',',explode("\n",trim($d['value'])));
                        }else{
                            $value = '';
                        }
                        array_push($column_data,[$formid,$d['etiqueta'],$d['tipo'],$d['orden'],$value]);
                    }
                    $db->createCommand()->batchInsert('form_field',$column,$column_data)->execute();
                }
                $transaction->commit();
                return $this->asJson(['code'=>0,'msg'=>'添加成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'添加失败','data'=>$exception->getMessage()]);
            }
        }
        return $this->render('create');
    }

    public function actionEdit()
    {
        $form_id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $db = $this->callcenter_db;
            $transaction = $db->beginTransaction();
            try{
                //更新form表
                $db->createCommand()->update('form',[
                    'nombre' => $data['nombre'],
                    'descripcion' => $data['descripcion'],
                ],['id' => $form_id])->execute();
                //更新form_field表
                if (!empty($data['form_fields'])){
                    //取出需要删除的ID
                    $need_delete_ids = [];
                    foreach ($data['form_fields'] as $d){
                        if ($d['field-id']){
                            array_push($need_delete_ids,$d['field-id']);
                        }
                    }
                    if (!empty($need_delete_ids)){
                        $db->createCommand()->delete('form_field',['and','id_form'=>$form_id,['not in','id',$need_delete_ids]])->execute();
                    }
                    foreach ($data['form_fields'] as $d){
                        if ($d['tipo']=='LIST' && $d['value'] ){
                            $value = implode(",",explode("\n",trim($d['value'])));
                        }else{
                            $value = '';
                        }
                        //新增的字段
                        if ($d['field-id']==0){
                            $db->createCommand()->insert('form_field',[
                                'id_form' => $form_id,
                                'etiqueta' => $d['etiqueta'],
                                'value' => $value,
                                'tipo' => $d['tipo'],
                                'orden' => $d['orden'],
                            ])->execute();
                        }else{
                            $db->createCommand()->update('form_field',[
                                'etiqueta' => $d['etiqueta'],
                                'value' => $value,
                                'tipo' => $d['tipo'],
                                'orden' => $d['orden'],
                            ],['id'=>$d['field-id'],'id_form' => $form_id])->execute();
                        }
                    }
                }
                $transaction->commit();
                return $this->asJson(['code'=>0,'msg'=>'更新成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'更新失败','data'=>$exception->getMessage()]);
            }
        }
        $form = (new Query())->from('form')->where(['id'=>$form_id])->one($this->callcenter_db);
        $form_fields = (new Query())->from('form_field')->where(['id_form'=>$form_id])->orderBy('orden asc')->all($this->callcenter_db);
        return $this->render('edit',['form'=>$form,'form_fields'=>$form_fields]);
    }

    /**
     * 删除表单
     * @return \yii\web\Response
     */
    public function actionDestroy()
    {
        $form_id = Yii::$app->request->post('id');
        //表单是否被使用
        $has_used = (new Query())->from('campaign_form')->where(['id_form'=>$form_id])->count('id_form',$this->callcenter_db);
        if ($has_used){
            return $this->asJson(['code'=>1,'msg'=>'表单已被使用，禁止删除']);
        }
        $db = $this->callcenter_db;
        $transaction = $db->beginTransaction();
        try{
            //先删除form_field表
            $db->createCommand()->delete('form_field',['id_form' => $form_id])->execute();
            //删除form表
            $db->createCommand()->delete('form',['id' => $form_id])->execute();
            $transaction->commit();
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            $transaction->rollBack();
            return $this->asJson(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }

    public function actionStatus()
    {
        $ids = Yii::$app->request->post('ids');
        $estatus = Yii::$app->request->post('estatus');
        if (empty($ids) || !is_array($ids) ){
            return $this->asJson(['code'=>1,'msg'=>'请选择操作项']);
        }
        if ($this->callcenter_db->createCommand()->update('form',['estatus'=>$estatus],['id'=>$ids])->execute()){
            return $this->asJson(['code'=>0,'msg'=>'操作成功']);
        }
        return $this->asJson(['code'=>1,'msg'=>'操作失败']);
    }

}